package com.erb.reciver;

import com.erb.common.Constant;
import com.erb.constants.AdminInformConstants;
import com.erb.constants.AdminProductConstants;
import com.erb.constants.RabbitMqConstants;
import com.erb.entity.*;
import com.erb.service.llb.IOtherService;
import com.erb.service.llb.InvestService;
import com.erb.service.zwj.IInformService;
import com.erb.service.zwj.IProductService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class UserInvestReciver {

	public static final Logger logger = LoggerFactory.getLogger(UserInvestReciver.class);

	@Autowired
	IOtherService otherService;
	@Autowired
	IProductService productService;
	@Autowired
	InvestService investService;
	@Autowired
	IInformService informService;

	@RabbitListener(queues = RabbitMqConstants.ERB_QUEUE_NAME)
	public void handler(Message message, Channel channel) throws IOException {
		Invest invest = (Invest) message.getPayload();
		MessageHeaders headers = message.getHeaders();
		Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
		try {
			//投资的项目
			Product product = productService.findProductById(invest.getPid());

			//添加资金记录
			CapitalLog capitalLog = new CapitalLog();
			capitalLog.setUid(invest.getUid());
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			capitalLog.setTradeDate(simpleDateFormat.format(new Date()));

			Double tradeMoney = invest.getInvestMoney();
			//如果使用了红包
			if (null != invest.getRid() && 0 != invest.getRid()) {
				Redpacketrecord redpacketrecord = otherService.findRedById(invest.getRid());
				tradeMoney = tradeMoney - redpacketrecord.getAmount();
			}
			capitalLog.setTradeMoney(tradeMoney * -1);
			capitalLog.setType(Constant.PURCHASE_ITEMS);
			capitalLog.setRemark("购买 " + product.getPname() + " 项目");
			otherService.addCapitalLog(capitalLog);
			logger.info("添加资金记录成功");

			//给用户发消息
			Inform inform = new Inform();
			inform.setInformTitle("投资成功！");
			inform.setInformContent("恭喜您投资 [" + product.getPname() + "] 成功！投资金额为" + invest.getInvestMoney() + "元,预计收益" + invest.getProfit() + "元。");
			inform.setInformSenderId(AdminInformConstants.ADMIN_ID_LABEL);
			inform.setInformRecipientsId(invest.getUid());
			inform.setSendTime(System.currentTimeMillis());
			informService.saveInform(inform);
			logger.info("发送消息成功");

			//判断投资的项目是否满标
            /*//如果是散标
            if (product.getType() == AdminProductConstants.PRODUCT_TYPE_CONVERSION_LOAN) {
                //剩余可投
                Double m = product.getTotal() - product.getHaveMoney();
                if (m > 0) {
                    //说明标未满 则招标中 不计算收益
                    logger.info("散标项目["+product.getPid()+"]未满标");
                } else {
                    //否则 把投这个项目的所有投资改为收益中
                    logger.info("散标项目["+product.getPid()+"]已满标 投资开始收益");
                    investService.updateStatusByPid(invest.getPid(), InvestConstants.INVEST_STATUS_RETURN);
                    *//*List<Invest> thisInvests = investService.findByPid(invest.getPid());
                    thisInvests.forEach(thisInvest -> {
                        investService.updateStatus(thisInvest.getId(),InvestConstants.INVEST_STATUS_RETURN);
                    });*//*
                    //改变该项目的状态为还款中
                    otherService.updateProductStatus(product.getPid(),AdminProductConstants.PRODUCT_STATUS_PAYMENT);
                    Product p = new Product();
                    p.setPid(product.getPid());
                    p.setSuccessTime(new Timestamp(System.currentTimeMillis()));
                    //更新项目成功交易时间
                    productService.modifyProduct(p);
                }
            } else { //平台标
                //剩余可投
                Double m = product.getTotal() - product.getHaveMoney();
                if (m > 0) {
                    logger.info("平台项目["+product.getPid()+"]未满标");
                } else {
                    logger.info("平台项目["+product.getPid()+"]已满标");
                    //改变该项目的状态为已满标
                    otherService.updateProductStatus(product.getPid(),AdminProductConstants.PRODUCT_STATUS_PAYMENT);
                    Product p = new Product();
                    p.setPid(product.getPid());
                    p.setSuccessTime(new Timestamp(System.currentTimeMillis()));
                    //更新项目成功交易时间
                    productService.modifyProduct(p);
                }
            }*/
			//剩余可投
			Double m = product.getTotal() - product.getHaveMoney();
			if (m > 0) {
				logger.info("项目[" + product.getPid() + "]未满标");
			} else {
				logger.info("项目[" + product.getPid() + "]已满标");
				//改变该项目的状态为已满标
				otherService.updateProductStatus(product.getPid(), AdminProductConstants.PRODUCT_STATUS_PAYMENT);
				Product p = new Product();
				p.setPid(product.getPid());
				p.setSuccessTime(new Timestamp(System.currentTimeMillis()));
				//更新项目成功交易时间
				productService.modifyProduct(p);
			}

			//确认消息消费
			channel.basicAck(tag, false);
		} catch (Exception e) {
			e.printStackTrace();
			//否认消息
			channel.basicNack(tag, false, true);
		}


	}
}
